from functools import reduce


# map将传入的函数依次作用到序列的每个元素，并把结果作为新的Iterator返回
# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上，这个函数必须接收两个参数，reduce把结果继续和序列的下一个元素做累积计算，其效果就是：
# reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)


def f(x):
    return x * x


result = map(f, [1, 2, 3, 4, 5])

print(list(result))  # result是一个惰性序列

print(list(map(str, [1, 3, 5, 7])))


def add(x, y):
    return x + y

a_sum = reduce(add, range(11))
print(a_sum)


def fn(x, y):
    """
    将序列转为整数
    :param x:
    :param y:
    :return:
    """
    return x * 10 + y

print(reduce(fn, range(10)))


def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]  # 一个字典 [s]是key

print(reduce(fn, map(char2num, '135246')))


def normalize(name):
    return name.capitalize()

print(list(map(normalize, ['jzq', 'MrX'])))


def prod(a_list):
    return reduce(lambda x, y: x * y, a_list)


print('2 * 3 * 4 * 5 = ', prod([2, 3, 4, 5]))


def str2float(s):
    return reduce(fn, map(char2num, s.split('.')[0])) \
           + reduce(fn, map(char2num, s.split('.')[1])) / pow(10, len(s.split('.')[1]))

print(str2float('123.456'))
